package com.itheima.demo;

import java.util.Arrays;

public class demo_002 {
    //二分查找;
    public static void main(String[] args) {
        //创建一个数组;
        int[] arr = {23, 46, 86, 32, 89, 1, 4, 9};
        //Arrays.sort(arr);
        //System.out.println("排序后的数组"+Arrays.toString(arr));
        //使用冒泡对数组进行排序;
        //外循环控制循环次数,
        for (int i = 0; i < arr.length - 1; i++) {
            //内循环控制比较的次数;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
        int num = 32;
        int index = method(arr, num);
        System.out.println("数字[" + num + "]所在的索引位置是:\t" + index);
    }

    //min+(max-min)
    private static int method(int[] arr, int num) {
        int min = 0;
        int max = arr.length - 1;
        while (min <= max) {
            //找出中间索引的值;
            int mid = min + (max - min) / 2;
            if (arr[mid] < num) {
                min = mid + 1;
            } else if (arr[mid] > num) {
                max = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
